<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>用户管理</span>
        <el-button type="primary" @click="openCreateUserDrawer">新增用户</el-button>
      </div>
    </template>
    <el-table :data="tableData" stripe :height="600" style="width: 100%">
      <el-table-column prop="userId" label="用户名"/>
      <el-table-column prop="email" label="邮箱"/>
      <el-table-column prop="roleName" label="角色"/>
      <el-table-column prop="hotelName" label="管理酒店">
        <template #default="{ row }">
          <span v-if="row.hotelName">{{ row.hotelName }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" circle @click="openUpdateUserDrawer(row)"/>
          <el-button type="danger" :icon="Delete" circle @click="handleDelete(row)"/>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-box">
      <el-pagination background layout="total, sizes, prev, pager, next"
                     v-model:current-page="pageIndex"
                     v-model:page-size="pageSize"
                     :page-sizes="[10, 20, 50, 100]"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :total="total"/>
    </div>
    <create-user ref="createUserRef" @refresh="initData"/>
    <update-user ref="updateUserRef" @refresh="initData"/>
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getUserList, deleteUser, getUserRoles } from '@/api/user'
import { Edit, Delete } from '@element-plus/icons-vue'
import CreateUser from './components/CreateUser.vue'
import UpdateUser from './components/UpdateUser.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const tableData = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(20)
const createUserRef = ref()
const updateUserRef = ref()

// 角色ID到角色名称的映射
const roleMap = {
  1: '用户',
  2: '酒店商家',
  3: '管理员'
}

// 获取用户角色ID的辅助函数
const getUserRoleId = (userData) => {
  // 尝试多种可能的数据结构
  
  // 1. 首先尝试从roles数组中获取
  if (userData.roles && userData.roles.length > 0) {
    const role = userData.roles[0];
    if (typeof role === 'object' && role !== null) {
      if (role.id !== undefined) return role.id;
      if (role.roleId !== undefined) return role.roleId;
      if (role.role_id !== undefined) return role.role_id;
    } else if (typeof role === 'number') {
      return role;
    }
  }
  
  // 2. 尝试从user对象中获取
  if (userData.user) {
    if (userData.user.roleId !== undefined) return userData.user.roleId;
    if (userData.user.role_id !== undefined) return userData.user.role_id;
  }
  
  // 3. 尝试从顶级对象获取
  if (userData.roleId !== undefined) return userData.roleId;
  if (userData.role_id !== undefined) return userData.role_id;
  
  return null; // 如果都没找到，返回null
}

const initData = () => {
  getUserList({}).then(res => {
    const result = res.data
    if (result.code === 200 && result.data) {
      // 输出返回的数据结构以便调试
      console.log('后端返回的用户数据:', result.data)
      
      // 处理新的返回数据结构，提取用户信息并填充角色名称
      tableData.value = result.data.map(item => {
        // 获取基本用户信息
        const userInfo = item.user;
        
        // 获取角色ID
        const roleId = getUserRoleId(item);
        console.log(`用户 ${userInfo.userId} 的角色ID:`, roleId);
        
        // 根据角色ID获取角色中文名称
        let roleName = '未分配';
        if (roleId !== null) {
          roleName = roleMap[roleId] || '未知角色';
        }
        
        // 返回处理后的用户数据
        return {
          ...userInfo,
          roleName: roleName,
          hotelName: item.hotelName || '' // 对于酒店商家，显示酒店名称
        };
      });
      total.value = result.data.length;
    }
  })
}
const handleSizeChange = (size: number) => {
  pageSize.value = size
  initData()
}
const handleCurrentChange = (index: number) => {
  pageIndex.value = index
  initData()
}
const openCreateUserDrawer = () => {
  createUserRef.value.open()
}
const openUpdateUserDrawer = (row: any) => {
  // 确保传递正确的用户ID和角色ID
  const userData = {
    userId: row.userId,
    email: row.email,
    roleId: getUserRoleId({ user: row, roleId: row.roleId }) || null,
    hotelName: row.hotelName
  };
  
  console.log('准备编辑的用户数据:', userData);
  updateUserRef.value.open(userData);
}
const handleDelete = (row: any) => {
  // 确保我们有正确的userId
  const userId = row.userId;
  
  if (!userId) {
    ElMessage.error('用户ID不能为空');
    return;
  }
  
  console.log('准备删除用户:', userId);
  
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', { type: 'warning' }).then(() => {
    deleteUser(userId).then(res => {
      const result = res.data
      if (result.code === 200) {
        ElMessage.success('删除成功')
        initData()
      } else {
        ElMessage.error(result.message || '删除失败')
      }
    }).catch(error => {
      console.error('删除用户失败:', error)
      ElMessage.error('网络错误，请稍后重试')
    })
  })
}
onMounted(() => {
  // 测试getUserRoleId函数
  console.log('=== 测试获取角色ID函数 ===');
  
  // 测试案例1: roles是对象数组，包含id
  const testCase1 = {
    user: { userId: 'test1', email: 'test1@example.com' },
    roles: [{ id: 1, name: '用户' }]
  };
  console.log('测试案例1 - 对象数组带id:', getUserRoleId(testCase1));
  
  // 测试案例2: roles是对象数组，包含roleId
  const testCase2 = {
    user: { userId: 'test2', email: 'test2@example.com' },
    roles: [{ roleId: 2, name: '酒店商家' }]
  };
  console.log('测试案例2 - 对象数组带roleId:', getUserRoleId(testCase2));
  
  // 测试案例3: roles是数值数组
  const testCase3 = {
    user: { userId: 'test3', email: 'test3@example.com' },
    roles: [3]
  };
  console.log('测试案例3 - 数值数组:', getUserRoleId(testCase3));
  
  // 测试案例4: roleId在user对象中
  const testCase4 = {
    user: { userId: 'test4', email: 'test4@example.com', roleId: 1 }
  };
  console.log('测试案例4 - roleId在user对象中:', getUserRoleId(testCase4));
  
  // 测试案例5: roleId在顶级对象中
  const testCase5 = {
    user: { userId: 'test5', email: 'test5@example.com' },
    roleId: 2
  };
  console.log('测试案例5 - roleId在顶级对象中:', getUserRoleId(testCase5));
  
  // 初始化数据
  initData()
})
</script>
<style scoped>
.header { display: flex; justify-content: space-between; align-items: center; }
.pagination-box { padding-top: 16px; display: flex; justify-content: right; }
</style>